package com.test.p10proxy.example01;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author bcc
 */
public class ValidatorInvocationHandler implements InvocationHandler {

    private Object target;

    public ValidatorInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        if (validate((String) args[0], (String) args[1])) {
            System.out.println((String) args[0] + "用户验证成功！");
            Object result = method.invoke(target, args);

            System.out.println("Validator返回...");
            return result;
        }
        return null;
    }

    /**
     * 返回经过 ValidatorInvocationHandler 包装的代理对象
     * @param target
     * @return
     */
    public static Object createProxy(Object target) {
        Class<?> allClass = target.getClass();
        return Proxy.newProxyInstance(allClass.getClassLoader(),allClass.getInterfaces(),new ValidatorInvocationHandler(target));
    }

    private boolean validate(String userName, String password) {
        AccessValidator validator = new AccessValidator();
        return validator.validateUser(userName, password);
    }
}
